/**
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *	
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */
package com.brightcove.android.oneplanet;

import java.util.logging.Logger;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.ListAdapter;
import android.widget.ListView;

import com.brightcove.android.oneplanet.view.PlaylistAdapter;
import com.brightcove.mobile.mediaapi.BCException;
import com.brightcove.mobile.mediaapi.ReadAPI;
import com.brightcove.mobile.mediaapi.model.ItemCollection;
import com.brightcove.mobile.mediaapi.model.Playlist;
import com.brightcove.mobile.mediaapi.model.enums.SortByTypeEnum;
import com.brightcove.mobile.mediaapi.model.enums.SortOrderTypeEnum;

/**
 * This is the first activity loaded when the One Planet app
 * starts.
 */
public class Playlists extends ListActivity {
	
	private final static String TAG = "Playlists";

	private Logger apiLogger;
	private ReadAPI readApi;
	
	private ItemCollection<Playlist> playlists;
	final Handler handler = new Handler();
	final Runnable updateResults = new Runnable() {
		public void run() {
			updateResultsInUi();
		}
	};	

	public Playlists() {
		apiLogger = Logger.getLogger("OnePlanet");
		readApi = new ReadAPI(APIToken.API_TOKEN);
		readApi.setLogger(apiLogger);
		
	}

	/** 
	 * Called when the activity is first created. 
	 */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.main);
        fetchPlaylists();
    }
    
    /**
     * Pings api.brightcove.com for the playlist data.
     */
    private void fetchPlaylists() {
        Thread t = new Thread() {
        	public void run() {
		        try {
					playlists =  readApi.findAllPlaylists(100, 0, false, 
							SortByTypeEnum.CREATION_DATE, SortOrderTypeEnum.DESC,
							null, null, null);
		
					handler.post(updateResults);
				} catch (BCException bce) {
					Log.d("Playlists", "BCException!>> " + bce.getMessage());
					bce.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}
        	}
        };
        t.start();
    }

    /**
     * This method is called when a ListView item is clicked / touched
     */
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
    	super.onListItemClick(l, v, position, id);
    	
    	Playlist playlist = (Playlist) getListAdapter().getItem(position);
    	Log.d(TAG, "clicked: " + playlist.getName());
    	
    	Intent i = new Intent(this, Videos.class);
    	AndroidPlaylist ap = new AndroidPlaylist(playlist);

    	i.putExtra(AndroidPlaylist.PLAYLIST, ap);
    	startActivity(i);
    }
    
    /**
     * After the data is loaded on a worker thread the ListView is updated
     * with the playlist data.
     */
    private void updateResultsInUi() {
        Playlist[] playlistArr = playlists.getItems().toArray(new Playlist[0]);
        ListAdapter adapter = new PlaylistAdapter<Playlist>(this,
        		android.R.layout.simple_list_item_1,
        		playlistArr);
        
        dissolveToList();
        setListAdapter(adapter);
    }

    /**
     * Adds two alpha animations when the app has data to render.
     */
	private void dissolveToList() {
		Animation fadeOut = new AlphaAnimation(1.0f, 0.0f);
        fadeOut.setDuration(500);
        
        Animation fadeIn = new AlphaAnimation(0.0f, 1.0f);
        fadeIn.setDuration(500);
        
        View emptyList = findViewById(android.R.id.empty);
        View list = findViewById(android.R.id.list);

        emptyList.startAnimation(fadeOut);
        list.startAnimation(fadeIn);
	}
}
